from typing import Any, Dict
from .Exporter import Exporter
import json
import os

class JsonExporter(Exporter):
    def write_output(self, data: Dict[str, Dict[str, Any]], output_path: str, file_name: str):
        with open(output_path, 'w', encoding='utf-8') as f:
            ret_str = "{\n"
            if len(data.keys()) == 0:
                ret_str += "}"
                f.write(ret_str)
                return

            is_first_sheet = True
            for sheet_name, sheet_data in data.items():
                if is_first_sheet:
                    is_first_sheet = False
                else:
                    ret_str += ",\n"

                ret_str += f'"{sheet_name}":{{'
                if len(sheet_data.keys()) == 0:
                    ret_str += "}"
                    continue

                ret_str += "\n"
                is_first_row = True
                for key, value in sheet_data.items():
                    if is_first_row:
                        is_first_row = False
                    else:
                        ret_str += ",\n"
                    ret_str += f'"{key}":{json.dumps(value, ensure_ascii=False, separators=(",", ":"))}'

                ret_str += "\n}"

            ret_str += "\n}"
            f.write(ret_str)
    
    def file_ext(self):
        return "json"